package com.example.javabasic.thread.classone.demo5;

import java.util.*;

/**
 * 数据采集模拟  实现类似线程池的概念
 */
public class ComputerService {
    //设置并行数
    private static final int SIZE = 2;
    private static Queue<Control> controlList = new ArrayDeque<>();


    public static void main(String[] args) {
        List<Thread> workerThread = new ArrayList<>();
        List<String> list = Arrays.asList("M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10");
        list.stream()
                .map(ComputerService::getThread)
                .forEach(t->{
                    t.start();
                    workerThread.add(t);
        });
        workerThread.forEach(t-> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Optional.of("所有线程执行完成").ifPresent(System.out::println);

    }

    /**
     * 创建线程
     * @param name
     * @return Thread
     */
    private static Thread getThread(String name){
        return new Thread(()->{
            //输出
            Optional.of("线程:"+Thread.currentThread().getName()+" 开始执行").ifPresent(System.out::println);
            synchronized (controlList){
                while(controlList.size()>=SIZE){
                    try {
                        controlList.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //添加到 队列头中
                controlList.offer(new Control());
            }
            Optional.of("线程"+Thread.currentThread().getName()+" 工作ing").ifPresent(System.out::println);
            try {
                //睡眠3秒代表执行任务
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (controlList){
                Optional.of("线程"+Thread.currentThread().getName()+" 结束运行").ifPresent(System.out::println);
                //删除队列尾 消费
                controlList.poll();
                //唤醒全部线程
                controlList.notifyAll();
            }

        },name);

    }

    /**
     * 静态内部类 用来做锁对象
     */
    private  static class Control{

    }
}
